import Taro, { Chain } from "@tarojs/taro";
import { TaroRequest } from "./request";

const codeErrorBehavior = {
  default: {
    message: "出错啦！请稍后重试！",
  },
  413: {
    message: "接口METHOD类型错误",
    behavior: (res) => {
      Taro.showModal({
        title: "错误",
        content: "接口METHOD类型错误",
        complete: () => {
          console.log(res);
        },
      });
    },
  },
};

const httpCodeBehavior = {
  // 404: {
  //   message: '测试4011114',
  //   behavior: detail => {
  //     // console.log(detail, detail);
  //   },
  // },
};

const responseCodeErrorHandle = (chain: Chain) => {
  const { requestParams } = chain;
  return chain.proceed(requestParams).catch((error) => {
    const { code } = error;
    const { behavior, message } = codeErrorBehavior[code] || {
      behavior: null,
      message: "",
    };
    behavior && behavior(error);

    return Promise.reject(message ? { message } : error);
  });
};

const errorHandle = (chain: Chain) => {
  const { requestParams } = chain;
  return chain
    .proceed(requestParams)
    .then((r: { responseData: { data: any; code: any } }) => {
      const { data, code } = r.responseData;
      if (code !== "0000") {
        return Promise.reject(r.responseData);
      }
      return data;
    })
    .catch((error: any) => {
      return Promise.reject(error);
    });
};

const request = TaroRequest.init({
  baseUrl: process.env.TARO_APP_API,
  header: {
    "content-type": "application/json",
  },
  httpCodeBehavior,
  interceptors: [
    responseCodeErrorHandle,
    errorHandle,
    function (chain) {
      const { requestParams } = chain;
      return chain.proceed(requestParams).then((response) => {
        // TODO 什么也不干 打印一下数据
        return response;
      });
    },
  ],
});

export default request;
